package com.meichis.mcsappframework.qrcode;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.*;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.meichis.mcsappframework.R;
import com.meichis.mcsappframework.qrcode.camera.CameraManager;
import com.meichis.mcsappframework.qrcode.decoding.CaptureActivityHandler;
import com.meichis.mcsappframework.qrcode.decoding.DecodeFormatManager;
import com.meichis.mcsappframework.qrcode.decoding.InactivityTimer;
import com.meichis.mcsappframework.qrcode.view.ViewfinderView;
import com.meichis.mcsappframework.utils.FilePathUtil;
import com.meichis.mcsappframework.utils.MessageTools;
import com.meichis.mcsappframework.utils.Tools;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.*;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 扫码界面，默认扫一个码返回，intent传入size>1，表示扫多个码，手动返回
 */
public class QRCodeActivity extends Activity implements Callback, OnClickListener, EasyPermissions.PermissionCallbacks {

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private static final int REQUEST_TAKE_PHOTO = 1;
    private String photo_path;
    private ProgressDialog mProgress;
    private Bitmap scanBitmap;
    private ListView qrcode_lv_codes;
    private int size;//一次扫多个码;
    private ArrayList<Map<String, String>> results;
    private MySimpleAdapter mySimpleAdapter;
    int textCodeColor;//多个码显示时码的颜色
    int textbgColor;//多个码显示时背景色
    int RemoveRepeat;//多个码显示时是否需要去掉重复项默认不需要
    int IsNeedSelectPhoto;//是否需要展示从图库选择
    int IsBugsellScan;//窜货扫码时
    private String CodeType;//扫码的类别
    private boolean isMessCode = false;
    private int MessCode = 0;
    private static final int PARSE_BARCODE_FAIL = 303;
    private static final int PAUSE_RESUME = 304;
    private boolean isBack = false;

    String[] permissions = {Manifest.permission.CAMERA};
    private final int PERMISSION_REQUEST_CODE = 101;
    private boolean isContinue = false;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mProgress != null && mProgress.isShowing()) {
                mProgress.dismiss();
            }
            switch (msg.what) {
                case PARSE_BARCODE_FAIL:
                    Toast.makeText(QRCodeActivity.this, getResources().getString(R.string.distinguish_failed), Toast.LENGTH_LONG).show();
                    break;
                case PAUSE_RESUME:
                    pause();
                    if (!isBack) {
                        resume();
                    }
                    break;
                default:
            }
        }

    };

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkPermission();
    }

    private void onCreate() {
        setContentView(R.layout.activity_qrcode);
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        size = getIntent().getIntExtra("size", 1);

        textCodeColor = getIntent().getIntExtra("CodeColor", 0);
        textbgColor = getIntent().getIntExtra("bgColor", 0);
        RemoveRepeat = getIntent().getIntExtra("RemoveRepeat", 0);
        IsNeedSelectPhoto = getIntent().getIntExtra("IsNeedSelectPhoto", 0);
        IsBugsellScan = getIntent().getIntExtra("IsBugsellScan", 0);
        CodeType = getIntent().getStringExtra("CodeType");
        if (CodeType != null && CodeType.equals("ONE_D_FORMATS")) {
            decodeFormats = new Vector<BarcodeFormat>();
            decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
        }

        qrcode_lv_codes = (ListView) findViewById(R.id.qrcode_lv_codes);
        results = new ArrayList<>();
        if (size > 1) {//扫多个码，手动返回
            mySimpleAdapter = new MySimpleAdapter(this, results, R.layout.list_text_item, new String[]{"Code"}, new int[]{R.id.tv});
            qrcode_lv_codes.setAdapter(mySimpleAdapter);
        }
        ((TextView) findViewById(R.id.include1).findViewById(R.id.titlebar_left_text)).setText(R.string.titlebar_confirm);
        ((TextView) findViewById(R.id.include1).findViewById(R.id.titlebar_title_text)).setText(R.string.turn_on_lights);
        ((TextView) findViewById(R.id.include1).findViewById(R.id.titlebar_right_text)).setText(R.string.turn_on_photo);
        if (IsNeedSelectPhoto != 0) {
            //判断是否显示相册选图片按钮
            ((TextView) findViewById(R.id.include1).findViewById(R.id.titlebar_right_text)).setVisibility(View.GONE);
        }

        findViewById(R.id.include1).findViewById(R.id.titlebar_left_text).setOnClickListener(this);
        findViewById(R.id.include1).findViewById(R.id.titlebar_title_text).setOnClickListener(this);
        findViewById(R.id.include1).findViewById(R.id.titlebar_right_text).setOnClickListener(this);

        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
    }

    /**
     * 自定义SimpleAdapter
     */
    public class MySimpleAdapter extends SimpleAdapter {

        private List<Map<String, String>> codesData;

        public MySimpleAdapter(Context context, List<Map<String, String>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            this.codesData = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView tv_QRcode = (TextView) view.findViewById(R.id.tv);
            //窜货扫码时需要改变码颜色和背景，设置文字和背景色
            if (textCodeColor != 0 && textbgColor != 0) {
                tv_QRcode.setTextColor(getResources().getColor(textCodeColor));
                tv_QRcode.setBackgroundResource(textbgColor);
            }
            tv_QRcode.setText(codesData.get(position).get("Code"));
            return view;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isContinue) {
            resume();
        }
    }

    @Override
    protected void onPause() {
        if (isContinue) {
            pause();
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    private void resume() {
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    private void pause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }


    /**
     * 处理扫描结果
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        String resultString = result.getText().replace("\uFEFF", "");
        //解码默认UTF-8，如果出现乱码，换GBK再试
        if (Tools.isMessyCode(resultString) && MessCode < 1) {
            isMessCode = true;
            MessCode++;
            hasSurface = true;
            onPause();
            onResume();
            return;
        }
        playBeepSoundAndVibrate();
        if (resultString.equals("") || barcode == null) {
            Toast.makeText(QRCodeActivity.this, R.string.scan_failed, Toast.LENGTH_SHORT).show();
        } else {
            if (!barcode.isRecycled())
                barcode.recycle();

            //窜货扫码规则
            if (IsBugsellScan != 0) {
                //如果扫码内容是17位，且最后两位是01，则判断为箱码，就只传前面15位。
                if (resultString.length() == 17 && resultString.substring(resultString.length() - 2).equals("01")) {
                    resultString = resultString.substring(0, resultString.length() - 2);
                } else {
                    //如果扫码内容有=号（为URL）的，则取=号后，如长度25位，则判定为听吗，则截取到86.1000.11/，传后面14位
                    if (resultString.indexOf("=") > 0 && resultString.startsWith("http://")) {
                        resultString = resultString.substring(resultString.lastIndexOf("=") + 1);
                        if (resultString.length() == 25 && resultString.indexOf("/") > 0) {
                            resultString = resultString.substring(resultString.lastIndexOf("/") + 1);
                        }
                    } else if (resultString.indexOf("=") == 0 && resultString.length() == 25 && resultString.indexOf("/") > 0) {//如果扫码内容没有=号的，且长度25位，则判定为听吗，则截取到86.1000.11/，传后面14位
                        resultString = resultString.substring(resultString.lastIndexOf("/") + 1);
                    }
                }
            }
            isMessCode = false;
            MessCode = 0;
            if (resultString.contains("资产编码") || resultString.contains("资产编号")) {
                String[] infos;
                if (resultString.contains("\r\n")) {
                    infos = resultString.split("\r\n");
                } else {
                    infos = resultString.split("\n");
                }
                for (String s : infos) {
                    if (s.contains("资产编码") || s.contains("资产编号")) {
                        resultString = s.substring(5);
                    }
                }
            }

            Map<String, String> map = new HashMap<>();
            map.put("Code", resultString);
            results.add(map);

            if (RemoveRepeat != 0) {
                //窜货扫码时判断是否需要去除重复的码
                removeDuplicate(results);
            }
            if (size > 1 && results.size() < size) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mySimpleAdapter.notifyDataSetChanged();
                        qrcode_lv_codes.setSelection(results.size());
                    }
                });
                mHandler.sendEmptyMessageDelayed(PAUSE_RESUME, 1500);//间隔1.5秒才能继续扫描
            } else {//扫一个码或者扫完size个数，立即返回
                onBackPressed();
            }
        }

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            if (isMessCode) {
                handler = new CaptureActivityHandler(this, decodeFormats, "gbk");
            } else {
                handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void onClick(View v) {
        //返回
        if (v.getId() == R.id.titlebar_left_text) {
            onBackPressed();
            return;
        }
        //开关灯
        if (v.getId() == R.id.titlebar_title_text) {
            if (((TextView) v).getText().toString().equals(getResources().getString(R.string.turn_on_lights))) {
                ((TextView) v).setText(getResources().getString(R.string.turn_off_lights));
                try {
                    CameraManager.get().openF();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                ((TextView) v).setText(getResources().getString(R.string.turn_on_lights));
                try {
                    CameraManager.get().stopF();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return;
        }
        //选取照片
        if (v.getId() == R.id.titlebar_right_text) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction("android.intent.action.GET_CONTENT");
            startActivityForResult(intent, REQUEST_TAKE_PHOTO);
        }

    }

//    /**
//     * 扫描二维码图片的方法
//     *
//     * @param path
//     * @return
//     */
//    MultiFormatReader multiFormatReader;
//
//    public Result scanningImage(String path) {
//        if (TextUtils.isEmpty(path)) {
//            return null;
//        }
//        multiFormatReader = new MultiFormatReader();
//        Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
//        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码
//
//        multiFormatReader.setHints(hints);
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true; // 先获取原大小
//        scanBitmap = BitmapFactory.decodeFile(path, options);
//        options.inJustDecodeBounds = false; // 获取新的大小
//        int sampleSize = (int) (options.outHeight / (float) 200);
//        if (sampleSize <= 0)
//            sampleSize = 1;
//        options.inSampleSize = sampleSize;
//        scanBitmap = BitmapFactory.decodeFile(path, options);
//        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
//        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
//        try {
//            return multiFormatReader.decodeWithState(bitmap1);
//        } catch (ReaderException re) {
//            // continue
//        } finally {
//            multiFormatReader.reset();
//        }
//
//        return null;
//    }

    @Override
    public void onBackPressed() {
        Intent resultIntent = getIntent();
        Bundle bundle = new Bundle();
        ArrayList<String> list = new ArrayList<>();
        for (Map<String, String> map : results) {
            list.add(map.get("Code"));
        }
        bundle.putStringArrayList("results", list);
        resultIntent.putExtras(bundle);
        this.setResult(RESULT_OK, resultIntent);
        isBack = true;
        super.onBackPressed();
    }

    @AfterPermissionGranted(PERMISSION_REQUEST_CODE)
    private void checkPermission() {

        if (EasyPermissions.hasPermissions(this, permissions)) {
            isContinue = true;
            onCreate();
        } else {
            EasyPermissions.requestPermissions(this, "当前需要相机权限！", PERMISSION_REQUEST_CODE, permissions);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        isContinue = true;
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        showWaringDialog();
    }

    private void showWaringDialog() {
        new AppSettingsDialog.Builder(this)
                .setTitle("无相机权限")
                .setRationale("可能会导致扫码功能无法正常使用,前往设置打开权限")
                .setPositiveButton("前往设置")
                .setNegativeButton("取消")
                .setRequestCode(PERMISSION_REQUEST_CODE)//用于onActivityResult回调做其它对应相关的
                .build().show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (EasyPermissions.hasPermissions(this, permissions)) {
                isContinue = true;
                onCreate();
            } else {
                MessageTools.showShortToast("相机权限未被允许！");
                finish();
            }
            return;
        }
        if (resultCode == Activity.RESULT_OK) {
            if (data.getData() == null) {
                Message m = mHandler.obtainMessage();
                m.what = PARSE_BARCODE_FAIL;
                mHandler.sendMessage(m);
                return;
            }
            photo_path = FilePathUtil.getFilePath(this, data.getData());

            mProgress = new ProgressDialog(this);
            mProgress.setMessage("正在扫描...");
            mProgress.setCancelable(false);
            mProgress.show();
            if (IsBugsellScan != 0) {
                //窜货模块识别二维码
                parsePhoto(photo_path);
            } else {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Result result = scanningImage(photo_path);
                        if (result != null) {
                            handleDecode(result, scanBitmap);
                            mProgress.dismiss();
                            //窜货模块，不返回上一页
                            if (IsBugsellScan != 0) {
                                return;
                            }
                            QRCodeActivity.this.finish();
                        } else {
                            mProgress.dismiss();
                            Message m = mHandler.obtainMessage();
                            m.what = PARSE_BARCODE_FAIL;
                            mHandler.sendMessage(m);
                        }
                    }
                }).start();
            }
        }
    }

    /**
     * 扫描二维码图片的方法
     *
     * @param path
     * @return
     */
    protected Result scanningImage(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;

        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取原大小
        scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false;
        int sampleSize = (int) (options.outHeight / (float) 200);
        if (sampleSize <= 0) {
            sampleSize = 1;
        }

        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);
        byte[] data = getYUV420sp(scanBitmap.getWidth(), scanBitmap.getHeight(), scanBitmap);

        Hashtable<DecodeHintType, Object> hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); // 设置二维码内容的编码
        hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
        PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, scanBitmap.getWidth(), scanBitmap.getHeight(), 0, 0, scanBitmap.getWidth(), scanBitmap.getHeight(), false);

        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader2 = new QRCodeReader();
        Result result = null;
        try {
            result = reader2.decode(bitmap1, hints);
        } catch (Exception e) {
        } finally {
            if (scanBitmap != null && !scanBitmap.isRecycled()) {
                scanBitmap.recycle();
            }

        }

        return result;


    }

    byte[] getYUV420sp(int inputWidth, int inputHeight, Bitmap scaled) {
        int[] argb = new int[inputWidth * inputHeight];

        scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight);

        byte[] yuv = new byte[inputWidth * inputHeight * 3 / 2];

        encodeYUV420SP(yuv, argb, inputWidth, inputHeight);

        scaled.recycle();

        return yuv;
    }

    void encodeYUV420SP(byte[] yuv420sp, int[] argb, int width, int height) {
        // 帧图片的像素大小
        final int frameSize = width * height;
        // ---YUV数据---
        int Y, U, V;
        // Y的index从0开始
        int yIndex = 0;
        // UV的index从frameSize开始
        int uvIndex = frameSize;

        // ---颜色数据---
//      int a, R, G, B;
        int R, G, B;
        //
        int argbIndex = 0;
        //

        // ---循环所有像素点，RGB转YUV---
        for (int j = 0; j < height; j++) {
            for (int i = 0; i < width; i++) {

                // a is not used obviously
//              a = (argb[argbIndex] & 0xff000000) >> 24;
                R = (argb[argbIndex] & 0xff0000) >> 16;
                G = (argb[argbIndex] & 0xff00) >> 8;
                B = (argb[argbIndex] & 0xff);
                //
                argbIndex++;

                // well known RGB to YUV algorithm
                Y = ((66 * R + 129 * G + 25 * B + 128) >> 8) + 16;
                U = ((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128;
                V = ((112 * R - 94 * G - 18 * B + 128) >> 8) + 128;

                //
                Y = Math.max(0, Math.min(Y, 255));
                U = Math.max(0, Math.min(U, 255));
                V = Math.max(0, Math.min(V, 255));
                yuv420sp[yIndex++] = (byte) Y;
            }
        }
    }


    /**
     * 去除重复项
     *
     * @param list
     * @return
     */
    public static ArrayList<Map<String, String>> removeDuplicate(ArrayList<Map<String, String>> list) {
        Set set = new LinkedHashSet<String>();
        set.addAll(list);
        list.clear();
        list.addAll(set);
        return list;
    }

    /**
     * 窜货模块使用
     * 启动线程解析二维码图片
     *
     * @param path
     */
    private void parsePhoto(String path) {
        //启动线程完成图片扫码
        new QrCodeAsyncTask(this, path).execute(path);
    }

    /**
     * AsyncTask 静态内部类，防止内存泄漏
     */
    static class QrCodeAsyncTask extends AsyncTask<String, Integer, String> {
        private WeakReference<Activity> mWeakReference;
        private String path;

        public QrCodeAsyncTask(Activity activity, String path) {
            mWeakReference = new WeakReference<>(activity);
            this.path = path;
        }

        @Override
        protected String doInBackground(String... strings) {
            // 解析二维码/条码
            return QRCodeDecoder.syncDecodeQRCode(path);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //识别出图片二维码/条码，内容为s
            QRCodeActivity activity = (QRCodeActivity) mWeakReference.get();
            if (activity != null) {
                activity.handleQrCode(s);
            }
        }
    }

    /**
     * 处理图片二维码解析的数据
     *
     * @param s
     */
    public void handleQrCode(String s) {
        if (mProgress != null) {
            mProgress.dismiss();
        }
        if (null == s) {
            Toast.makeText(getApplicationContext(), "识别失败", Toast.LENGTH_SHORT).show();
        } else {
            // 识别出图片二维码/条码，内容为s
            handleResult(s);
        }
    }

    private void handleResult(String result) {
        handleDecode(result);
    }

    /**
     * （处理扫描出来的窜货码）窜货模块使用
     * 处理扫描结果
     */
    public void handleDecode(String resultString) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        if (resultString.equals("")) {
            Toast.makeText(QRCodeActivity.this, R.string.scan_failed, Toast.LENGTH_SHORT).show();
        } else {
            //窜货扫码规则
            if (IsBugsellScan != 0) {
                //如果扫码内容是17位，且最后两位是01，则判断为箱码，就只传前面15位。
                if (resultString.length() == 17 && resultString.substring(resultString.length() - 2).equals("01")) {
                    resultString = resultString.substring(0, resultString.length() - 2);
                } else {
                    //如果扫码内容有=号（为URL）的，则取=号后，如长度25位，则判定为听吗，则截取到86.1000.11/，传后面14位
                    if (resultString.indexOf("=") > 0 && resultString.startsWith("http://")) {
                        resultString = resultString.substring(resultString.lastIndexOf("=") + 1);
                        if (resultString.length() == 25 && resultString.indexOf("/") > 0) {
                            resultString = resultString.substring(resultString.lastIndexOf("/") + 1);
                        }
                    } else if (resultString.indexOf("=") == 0 && resultString.length() == 25 && resultString.indexOf("/") > 0) {//如果扫码内容没有=号的，且长度25位，则判定为听吗，则截取到86.1000.11/，传后面14位
                        resultString = resultString.substring(resultString.lastIndexOf("/") + 1);
                    }
                }
            }

            Map<String, String> map = new HashMap<>();
            map.put("Code", resultString);
            results.add(map);

            if (RemoveRepeat != 0) {
                //窜货扫码时判断是否需要去除重复的码
                removeDuplicate(results);
            }
            if (size > 1 && results.size() < size) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mySimpleAdapter.notifyDataSetChanged();
                        qrcode_lv_codes.setSelection(results.size());
                    }
                });
                mHandler.sendEmptyMessageDelayed(PAUSE_RESUME, 1500);//间隔1.5秒才能继续扫描
            } else {//扫一个码或者扫完size个数，立即返回
                onBackPressed();
            }
        }

    }
}